<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>志愿者信息管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .action-buttons button {
            margin-right: 5px;
        }
        .form-container {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>志愿者信息管理系统</h1>

        <!-- 志愿者信息表单 -->
        <div class="form-container">
            <h2 id="formTitle">新增志愿者信息</h2>
            <form id="volunteerForm">
                <input type="hidden" id="volunteer_id">

                <div class="form-group">
                    <label for="user_id">用户ID:</label>
                    <input type="number" id="user_id" required>
                </div>

                <div class="form-group">
                    <label for="student_id">学号:</label>
                    <input type="text" id="student_id" required>
                </div>

                <div class="form-group">
                    <label for="gender">性别:</label>
                    <select id="gender" required>
                        <option value="0">女</option>
                        <option value="1">男</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="major">专业:</label>
                    <input type="text" id="major" required>
                </div>

                <div class="form-group">
                    <label for="grade">年级:</label>
                    <input type="text" id="grade" required>
                </div>

                <div class="form-group">
                    <label for="skill">技能:</label>
                    <input type="text" id="skill">
                </div>

                <div class="form-group">
                    <label for="total_hours">总服务时长:</label>
                    <input type="number" step="0.1" id="total_hours">
                </div>

                <button type="submit" class="btn btn-primary" id="saveBtn">保存</button>
                <button type="button" class="btn btn-warning" id="cancelBtn">取消</button>
            </form>
        </div>

        <!-- 志愿者信息列表 -->
        <div>
            <h2>志愿者信息列表</h2>
            <button class="btn btn-success" id="refreshBtn">刷新数据</button>
            <table id="volunteerTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户ID</th>
                        <th>学号</th>
                        <th>性别</th>
                        <th>专业</th>
                        <th>年级</th>
                        <th>技能</th>
                        <th>总服务时长</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="volunteerTableBody">
                    <!-- 数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
    // API基础URL
    const BASE_URL = '/volunteer_info';

    // DOM元素
    const volunteerForm = document.getElementById('volunteerForm');
    const volunteerTableBody = document.getElementById('volunteerTableBody');
    const refreshBtn = document.getElementById('refreshBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const formTitle = document.getElementById('formTitle');
    const saveBtn = document.getElementById('saveBtn');

    // 页面加载时获取所有志愿者信息
    document.addEventListener('DOMContentLoaded', function() {
        loadAllVolunteers();
    });

    // 刷新按钮事件
    refreshBtn.addEventListener('click', loadAllVolunteers);

    // 表单提交事件
    volunteerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        saveVolunteer();
    });

    // 取消按钮事件
    cancelBtn.addEventListener('click', resetForm);

    // 获取所有志愿者信息
    function loadAllVolunteers() {
        fetch(`${BASE_URL}/queryAll`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    renderVolunteerTable(data.data);
                } else {
                    alert('获取数据失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取数据时发生错误');
            });
    }

    // 渲染志愿者信息表格
    function renderVolunteerTable(volunteers) {
        volunteerTableBody.innerHTML = '';

        volunteers.forEach(volunteer => {
            const row = document.createElement('tr');
            // 修改这里：将onclick事件改为addEventListener方式
            row.innerHTML = `
                <td>${volunteer.volunteer_id}</td>
                <td>${volunteer.user_id}</td>
                <td>${volunteer.student_id}</td>
                <td>${volunteer.gender === 1 ? '男' : '女'}</td>
                <td>${volunteer.major}</td>
                <td>${volunteer.grade}</td>
                <td>${volunteer.skill || ''}</td>
                <td>${volunteer.total_hours || 0}</td>
                <td class="action-buttons">
                    <button class="btn btn-primary edit-btn" data-volunteer='${JSON.stringify(volunteer)}'>编辑</button>
                    <button class="btn btn-danger delete-btn" data-id="${volunteer.volunteer_id}">删除</button>
                </td>
            `;
            volunteerTableBody.appendChild(row);
        });

        // 为编辑按钮添加事件监听器
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', function() {
                const volunteer = JSON.parse(this.getAttribute('data-volunteer'));
                editVolunteer(volunteer);
            });
        });

        // 为删除按钮添加事件监听器
        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', function() {
                const volunteerId = this.getAttribute('data-id');
                deleteVolunteer(volunteerId);
            });
        });
    }

    // 保存志愿者信息（新增或更新）
    function saveVolunteer() {
        const volunteerData = {
            user_id: parseInt(document.getElementById('user_id').value),
            student_id: document.getElementById('student_id').value,
            gender: parseInt(document.getElementById('gender').value),
            major: document.getElementById('major').value,
            grade: document.getElementById('grade').value,
            skill: document.getElementById('skill').value,
            total_hours: parseFloat(document.getElementById('total_hours').value) || 0
        };

        const volunteerId = document.getElementById('volunteer_id').value;
        const isUpdate = !!volunteerId;

        if (isUpdate) {
            volunteerData.volunteer_id = parseInt(volunteerId);
        }

        const url = isUpdate ? `${BASE_URL}/update` : `${BASE_URL}/add`;
        // 关键修改：明确指定正确的HTTP方法
        const method = isUpdate ? 'PUT' : 'POST';

        fetch(url, {
            method: method,  // 这里是关键修改
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(volunteerData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert(isUpdate ? '更新成功' : '新增成功');
                resetForm();
                loadAllVolunteers();
            } else {
                alert(isUpdate ? '更新失败: ' + data.msg : '新增失败: ' + data.msg);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert(isUpdate ? '更新时发生错误' : '新增时发生错误');
        });
    }

    // 编辑志愿者信息
    function editVolunteer(volunteer) {
        document.getElementById('volunteer_id').value = volunteer.volunteer_id;
        document.getElementById('user_id').value = volunteer.user_id;
        document.getElementById('student_id').value = volunteer.student_id;
        document.getElementById('gender').value = volunteer.gender;
        document.getElementById('major').value = volunteer.major;
        document.getElementById('grade').value = volunteer.grade;
        document.getElementById('skill').value = volunteer.skill || '';
        document.getElementById('total_hours').value = volunteer.total_hours || 0;

        formTitle.textContent = '编辑志愿者信息';
        saveBtn.textContent = '更新';
    }

    // 删除志愿者信息
    function deleteVolunteer(volunteerId) {
        if (!confirm('确定要删除这个志愿者信息吗？')) {
            return;
        }

        fetch(`${BASE_URL}/delete/${volunteerId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('删除成功');
                loadAllVolunteers();
            } else {
                alert('删除失败: ' + data.msg);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除时发生错误');
        });
    }

    // 重置表单
    function resetForm() {
        volunteerForm.reset();
        document.getElementById('volunteer_id').value = '';
        formTitle.textContent = '新增志愿者信息';
        saveBtn.textContent = '保存';
    }
</script>

</body>
</html>
